from contextlib import asynccontextmanager
from fastapi import FastAPI
from common.config.env import AppConfig
from common.config.get_db import init_create_table,keepalive_db
from common.config.get_redis import RedisUtil
from common.exceptions.handle import handle_exception
from common.manager.mqtt.mqtt_init_manager import MQTTInitManager
from common.middlewares.handle import handle_middleware
from common.sub_applications.handle import handle_sub_applications
from common.utils.common_util import worship
from common.utils.log_util import logger
from urls import url_list
import asyncio
import os
import importlib
from common.utils.scheduler import scheduler

# 生命周期事件
@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info(f'{AppConfig.app_name}开始启动')
    worship()
    # 初始化数据库并检查结果
    db_initialized = await init_create_table()
    # 初始化Redis并检查结果
    app.state.redis = await RedisUtil.create_redis_pool()
    logger.info(f'{AppConfig.app_name}启动成功')
    # 仅在Redis连接成功时启动心跳检测
    if app.state.redis:
        asyncio.create_task(RedisUtil.keepalive(app.state.redis))
    # 仅在数据库初始化成功时启动心跳检测
    if db_initialized:
        asyncio.create_task(keepalive_db())
    # 初始化 MQTT 客户端管理器
    MQTTInitManager.start_mqtt_creation()
    scheduler.start()
    yield
    # 关闭 MQTT 客户端
    MQTTInitManager.stop_mqtt_clients()
    # 停止 MQTT 线程
    MQTTInitManager.stop_mqtt_thread()
    await RedisUtil.close_redis_pool(app)
    scheduler.shutdown()


# 初始化FastAPI对象
app = FastAPI(
    title=AppConfig.app_name,
    description=f'{AppConfig.app_name}接口文档',
    version=AppConfig.app_version,
    lifespan=lifespan,
    openapi_url=None,
    docs_url=None,
    redoc_url=None,
)


# 挂载子应用
handle_sub_applications(app)
# 加载中间件处理方法
handle_middleware(app)
# 加载全局异常处理方法
handle_exception(app)

# 加载路由列表
controller_list = [

]
controller_list.extend(url_list)
for controller in controller_list:
    app.include_router(router=controller.get('router'),prefix=controller.get('prefix'),tags=controller.get('tags'))